package com.dhcy.mqtt.dao;


import cn.hutool.core.util.ObjectUtil;
import com.dhcy.mqtt.util.CommGson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class RedisDao {
	@Autowired
	private JedisPool jedisPool;
	@Value("${spring.redis.password}")
	String password;

	public String getValue(String key) {
		String value = null;
		Jedis jedis = jedisPool.getResource();
		if (ObjectUtil.isNotEmpty(password)){
			jedis.auth(password);
		}
		value = jedis.get(key);
		jedis.close();
		return value;
	}

	public <T> T getObject(String key, Class<T> t) {
		String value = null;
		Jedis jedis = jedisPool.getResource();
		value = jedis.get(key);
		jedis.close();
		if (StringUtils.isBlank(value)) {
			return null;
		} else {
			return CommGson.getInstance().toObject(value, t);
		}
	}

	public void putValue(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		jedis.setex(key, 3, value);
		jedis.close();
	}

	public void putSecondValue(String key, String value, int seconds) {
		Jedis jedis = jedisPool.getResource();
		if (ObjectUtil.isNotEmpty(password)){
			jedis.auth(password);
		}
		jedis.setex(key, seconds, value);
		jedis.close();
	}

	public void putForeverValue(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		jedis.set(key, value);
		jedis.close();
	}

	 public void hmset(String key, Map<String, String> hash) {
		 Jedis jedis = jedisPool.getResource();
		 jedis.hmset(key, hash);
		 jedis.close();
	 }
	 public Map<String, String> getMap(String key) {
		 Jedis jedis = jedisPool.getResource();
		 Map<String, String> map = jedis.hgetAll(key);
		 jedis.close();
		 return map;
	 }


	//模糊查询
	public Map<String, String> getLikeValue(String likekey) {
		Jedis jedis = jedisPool.getResource();
		Set<String> keys = jedis.keys(likekey);
		Map<String, String> map = new HashMap<>();
		for (String key : keys) {
			map.put(key, jedis.get(key));
		}
		return map;
	}
	  //根据key删除
    public  void deleteKey(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            if (jedis != null) {
                jedis.del(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
